package com.drore.app.utils;

import android.content.Context;
import android.util.Log;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * desc
 *
 * @author sixbing
 * @date 2018/11/7 10:55
 */

public class DeleteFileUtil {
    private static String TAG = "DeleteFileUtil";
    //    static ArrayList<Object> name = new ArrayList<Object>();
    private static long mDays = 5;

    /**
     * 删除过期文件
     *
     * @param context    文本
     * @param filterPath 文件夹路径
     * @param days       过期天数
     */
    public static void del(Context context, String filterPath, long days) {
        mDays = days;
        File file = new File(filterPath);
        File[] files = file.listFiles();// 读取
        getFileName(files, context);
    }

    private static void getFileName(File[] files, Context context) {
        if (files != null) {// 先判断目录是否为空，否则会报空指针
            for (File file : files) {
                if (file.isDirectory()) {
                    Log.i(TAG, "若是文件目录。继续读1" + file.getName().toString()
                            + file.getPath().toString());
                    getFileName(file.listFiles(), context);
//                    Log.i(TAG, "若是文件目录。继续读2" + file.getName().toString()
//                            + file.getPath().toString());
                } else {
                    long time = file.lastModified();//返回文件最后修改时间，是以个long型毫秒数
                    String stime = new SimpleDateFormat("yyyy-MM-dd HH:MM:ss").format(new Date(time));
                    String ctime = new SimpleDateFormat("yyyy-MM-dd HH:MM:ss").format(new Date());
                    try {
                        if (daysBetween(stime, ctime) > mDays) {
                            file.delete();
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 计算两个日期之间相差的天数
     * 字符串的日期格式的计算
     */
    public static long daysBetween(String smdate, String bdate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(smdate));
        long time1 = cal.getTimeInMillis();
        cal.setTime(sdf.parse(bdate));
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1);
//        int days = Integer.parseInt(String.valueOf(between_days));
//        cal.clear();
//        cal = null;
        return between_days;
    }
}
